﻿using System;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Web;

namespace 测试签名01
{
  

    public class TokenUtils
    { 
        private static readonly string[] HexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

        public static string GetSignature(string appPwd, string paramUrl)
        {
            if (!string.IsNullOrWhiteSpace(paramUrl))
            {
                try
                {
                    paramUrl = HttpUtility.UrlDecode(paramUrl);
                }
                catch (Exception ex)
                { 
                    throw new Exception("生成 signData 失败", ex);
                }
            }

            string[] paraArray = Array.Empty<string>();
            if (!string.IsNullOrWhiteSpace(paramUrl))
            {
                string[] queryArray = paramUrl.Split('&');
                paraArray = queryArray;
            }

            Array.Sort(paraArray);
            StringBuilder buffer = new StringBuilder();
            buffer.Append(appPwd);
            buffer.Append(":");

            for (int i = 0; i < paraArray.Length; i++)
            {
                buffer.Append(paraArray[i]);
                buffer.Append("&");
            }

            if (buffer.Length > 0)
            {
                buffer.Length--; // Remove last '&'
            }

            buffer.Append(":");
            buffer.Append(appPwd);

            try
            {
                using (SHA256 sha256 = SHA256.Create())
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(buffer.ToString());
                    byte[] hash = sha256.ComputeHash(bytes);
                    return ByteArrayToHexString(hash);
                }
            }
            catch (Exception ex)
            { 
                throw new Exception("生成 signData 失败", ex);
            }
        }

        private static string ByteArrayToHexString(byte[] byteArray)
        {
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteArray)
            {
                sb.Append(ByteToHexString(b));
            }
            return sb.ToString();
        }

        private static string ByteToHexString(byte b)
        {
            int n = b;
            if (n < 0)
                n = 256 + n;
            return HexDigits[n / 16] + HexDigits[n % 16];
        }
    }
}
